package com.quectel.cms.controller.household;


import com.fasterxml.jackson.databind.JsonNode;
import com.quectel.business.common.util.sys.SysCodeUtils;
import com.quectel.cms.controller.BaseController;
import com.quectel.constant.core.household.HouseholdConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.constant.sys.SysCodeKeyConstants;
import com.quectel.core.module.household.dto.HouseholdDto;
import com.quectel.core.module.household.dto.HouseholdFollowLogDto;
import com.quectel.core.module.household.service.HouseholdFollowLogService;
import com.quectel.core.module.household.service.HouseholdService;
import com.quectel.util.common.JacksonUtils;
import com.quectel.util.common.Page;
import com.quectel.util.common.Request;
import com.quectel.util.common.Response;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhangheng
 * @email nolan.zhang@quectel.com
 * @date 2023/03/10 11:46
 */
@RestController
@RequestMapping("householdFollowLog")
@Tag(name = "HouseholdFollowLogController", description = "重点住户跟进相关api")
public class HouseholdFollowLogController extends BaseController {

    @DubboReference
    private HouseholdService householdService;
    @DubboReference
    private HouseholdFollowLogService householdFollowLogService;

    /**
     * 重点住户记录分页查询列表
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("list")
    @RequirePermissions(values = {"householdSocialRelations:list", "householdFollowLog:followRecord"})
    @Operation(summary = "重点住户记录分页查询列表")
    public Response<Page<HouseholdFollowLogDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());

        //按照跟进时间倒序
        request.put(SystemConstants.SORT_ORDER_BY_KEY, HouseholdConstants.ASK_TIME);
        request.put(SystemConstants.SORT_ORDER_RULE_KEY, SystemConstants.SORT_ORDER_RULE_DESC);

        int total = householdFollowLogService.queryTotal(request.getParams());

        List<HouseholdFollowLogDto> list = null;
        if (total > 0) {
            list = householdFollowLogService.queryList(request.getParams());
        } else {
            list = new ArrayList<>();
        }

        Page<HouseholdFollowLogDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<HouseholdFollowLogDto>>ok().wrap(page);
    }

    private List<String> getContradictionNameList(HouseholdFollowLogDto logDto) {
        List<String> nameList = new ArrayList<>();

        if (StringUtils.isNotEmpty(logDto.getContradictionJsonArr())) {
            List<JsonNode> jsonNodes = JacksonUtils.parseArray(logDto.getContradictionJsonArr());
            for (JsonNode jsonNode : jsonNodes) {
                nameList.add(SysCodeUtils.easyToGetName(SysCodeKeyConstants.SOCIAL_CONTRADICTIONS, jsonNode.textValue()));
            }
        }
        return nameList;

    }

    /**
     * 查询单条重点住户跟进记录，用于编辑查询反显
     *
     * @param id
     * @return
     */
    @GetMapping("infoForEdit/{id}")
    @RequirePermissions(values = {"householdSocialRelations:edit", "householdFollowLog:follow"})
    @Operation(summary = "查询单条重点住户跟进记录，用于编辑查询反显")
    public Response<HouseholdFollowLogDto> infoForEdit(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (householdFollowLogService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        HouseholdFollowLogDto householdFollowLogDto = householdFollowLogService.selectById(id);
        householdFollowLogDto.setContradictionNameList(getContradictionNameList(householdFollowLogDto));

        return Response.<HouseholdFollowLogDto>ok().wrap(householdFollowLogDto);
    }

    /**
     * 查询单条重点住户跟进记录
     *
     * @param id
     * @return
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = {"householdSocialRelations:info", "householdFollowLog:followRecord", "gridHouseholdFollowLog:followRecord"})
    @Operation(summary = "查询单条重点住户跟进记录")
    public Response<HouseholdFollowLogDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (householdFollowLogService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        HouseholdFollowLogDto householdFollowLogDto = householdFollowLogService.selectById(id);
        householdFollowLogDto.setContradictionNameList(getContradictionNameList(householdFollowLogDto));

        return Response.<HouseholdFollowLogDto>ok().wrap(householdFollowLogDto);
    }

    /**
     * 保存
     *
     * @param householdFollowLogDto
     * @return
     */
    @PostMapping("save")
    @RequirePermissions(values = {"householdSocialRelations:edit", "householdFollowLog:follow"})
    @Operation(summary = "保存单条重点住户跟进记录")
    public Response<Object> save(@RequestBody @Validated HouseholdFollowLogDto householdFollowLogDto) {

        HouseholdDto householdDto = householdService.selectCacheById(householdFollowLogDto.getHouseholdId());
        if (householdDto == null) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        //填充基础数据
        fillSaveCommonData(householdFollowLogDto);

        householdFollowLogDto.setTenantId(householdDto.getTenantId());
        householdFollowLogDto.setVillageId(householdDto.getVillageId());
        //来源
        householdFollowLogDto.setSourceType(HouseholdConstants.FollowSourceType.SYS_USER.getType());

        householdFollowLogService.save(householdFollowLogDto);

        return Response.ok();
    }


    /**
     * 修改
     *
     * @param householdFollowLogDto
     * @return
     */
    @PostMapping("update")
    @RequirePermissions(values = {"householdSocialRelations:edit", "householdFollowLog:follow"})
    @Operation(summary = "修改重点住户跟进记录")
    public Response<Object> update(@RequestBody @Validated HouseholdFollowLogDto householdFollowLogDto) {

        HouseholdDto householdDto = householdService.selectCacheById(householdFollowLogDto.getHouseholdId());
        if (householdDto == null) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(householdFollowLogDto.getId()));
        if (householdFollowLogService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        //填充基础数据
        fillEditCommonData(householdFollowLogDto);

        householdFollowLogService.updateById(householdFollowLogDto);

        return Response.ok();
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @PostMapping("delete")
    @RequirePermissions(values = "householdFollowLog:delete")
    @Operation(summary = "批量删除重点住户跟进记录")
    public Response<Object> delete(@RequestBody Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (householdFollowLogService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }
        }

        householdFollowLogService.deleteBatch(ids);

        return Response.ok();
    }
}
